<script setup>
import { ref, computed, onMounted, onActivated } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/store';
import { useDebounceFn } from '@vueuse/core'
import { showToast } from 'vant';
import { event } from 'vue-gtag'

import { fetchRewardsDetails } from '@/api/withdraw.js'

import { useLoadAdxReward } from '@/utils/adx.js'
import { TurntableBanner, TurntableReward } from '/public/adConfig.js'

import BiNavBar from '@/components/biNavbar/index.vue'
import BiPopup from '@/components/biPopup/index.vue'
import TurnTableGame from './components/turntableGame/index.vue'
import LotteryBtn from '@/components/lotteryBtn/index.vue'
import Ad from '@/components/ad/index.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const notLotteryCount = computed(() => {
    return userStore.turntableCount == userStore.turntableCountTotal
})

const hideReward = ref(false)

const showRewardsPopup = ref(false)
function openRewardsPopup() {
    showRewardsPopup.value = true
}
function closeRewardsPopup() {
    showRewardsPopup.value = false
}

const popupType = computed(() => {
    return hideReward.value ? 'task' : 'normal'
})
const rewardsPopupBtnText = computed(() => {
    return notLotteryCount.value ? 'Get More' : 'Play Again'
})
const handleRewardsPopupFn = useDebounceFn(() => {
    const fn = notLotteryCount.value ? handleGetMoreRewards : handleWatchRewardAd
    fn()
}, 500)

const { init } = useLoadAdxReward(
    '',
    {
        emptyCallback: () => {
            showToast('Ad is loading. Please try again later.')
        },
        endCallback: () => { handleGetRewardsDetails() }
    }
)

function handleWatchRewardAd() {
    showRewardsPopup.value && closeRewardsPopup()

    init()
}

const handleActionGameFn = useDebounceFn(() => {
    if (notLotteryCount.value) {
        hideReward.value = true
        openRewardsPopup()
    } else {
        handleWatchRewardAd()
    }
    event('点击转盘按钮', {
        userId: userStore.uuid
    })
}, 500)

const loading = ref(false)
async function handleGetRewardsDetails() {
    loading.value = true
    try {
        const res = await fetchRewardsDetails({
            device: userStore.uuid,
            type: 2 // 转盘
        })
        userStore.handleGetUserInfo()
        rewards.value = res.data.data
        turnTableGame.value.handleStart()
        loading.value = false
    } catch (error) {
        loading.value = false
        throw new Error(error)
    }
}

const turnTableGame = ref() // turnTableGame 组件
function initTurntable() {
    turnTableGame.value.initTurntable()
}

const hasEggCount = computed(() => {
    return userStore.eggCount < userStore.eggCountTotal
})
const rewardsPopupTips = computed(() => {
    return hasEggCount.value ? `Enter the "Easter Egg" to get more rewards!` : 'Watch AD to get more rewards!'
})

const rewards = ref({})
const rewardIcon = computed(() => {
    const rewardType = {
        1: 'coin',
        2: 'cash'
    }
    return rewardType[rewards.value.currency]
})

function handleGetMoreRewards() {
    if (hasEggCount.value) {
        router.push({
            path: '/egg',
            query: {
                playAd: 1
            }
        })
    } else {
        handleWatchRewardAd()
    }
}
onMounted(() => {
    if (route.query.playAd && !notLotteryCount.value) {
        handleWatchRewardAd()
    }
})

const popupProps = computed(() => {
    return {
        type: popupType.value,
        buttonText: rewardsPopupBtnText.value,
        rewardsType: rewardIcon.value,
        rewardsNum: rewards.value.number,
        tips: rewardsPopupTips.value,
        displayTips: notLotteryCount.value
    }
})
</script>

<template>
    <BiNavBar @click-left="router.push({
        path: '/task'
    })" background="transparent" :shadow="false" left-text="Lucky Wheel" left-text-size="24px" arrow-size="4.5vmin">
    </BiNavBar>

    <img class="game-normal-bg" src="@/assets/imgs/bg.png" alt="">

    <img class="game-fire" src="@/assets/imgs/egg/fireworks.png" alt="firework">

    <main class="main">
        <TurnTableGame ref="turnTableGame" @end="openRewardsPopup" />
        <LotteryBtn @click="handleActionGameFn" :loading="loading" style="margin-top: 5vmin;">
            Play ({{ userStore.turntableCount }}/{{ userStore.turntableCountTotal }})
        </LotteryBtn>
    </main>

    <!-- <Ad :path="TurntableBanner.path" :id="TurntableBanner.id" :size="[300, 250]" style="margin-top: 4vmin;" /> -->

    <!-- 转盘奖励弹窗 -->
    <BiPopup v-model:show="showRewardsPopup" v-bind="popupProps" @click="handleRewardsPopupFn" @close="initTurntable">
        <span v-if="hideReward" class="red-text">{{ rewardsPopupTips }}</span>
    </BiPopup>

</template>

<style scoped lang="scss">
@import url(./turntable.scss);
</style>